package com.example.gokchinesefoodmapmcdev.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.gokchinesefoodmapmcdev.dao.SysRoleDAO;
import com.example.gokchinesefoodmapmcdev.dao.SysUserDAO;
import com.example.gokchinesefoodmapmcdev.entity.sys.SysRole;
import com.example.gokchinesefoodmapmcdev.entity.sys.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * 自定义用户信息验证
 * 从数据库中取出数据判断用户登录是否能够成功
 */
@Service
public class MyUserDetailService implements UserDetailsService {
    /**
     * 角色前缀名
     */
    private final static String ROLE_PREFIX = "ROLE_";

    @Autowired
    private SysUserDAO sysUserDAO;

    @Autowired
    private SysRoleDAO sysRoleDAO;

    /**
     * 1. 重写登录认证、权限认证的逻辑
     * 用户名、密码、权限 全部使用自己的数据库中的数据
     * 2. 使用JWT，生成token发送到前端浏览器
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SysUser user = sysUserDAO.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        /*
            从数据库中查出该用户的角色集合，
            然后存入权限集合中，交给Spring管理
         */
        // 查询角色集合
        List<SysRole> roles = sysRoleDAO.selectSysRolesByUsername(user.getUsername());
        // 放入权限集合
        Collection<GrantedAuthority> authorities = new HashSet<>();
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + role.getRoleName()));
        }

        // 存入Spring Security中UserDetails的默认实现类User中，返回
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), "{noop}" + user.getPassword(),
                true, true, true, true,
                authorities
        );

    }
}
